package com.example.demo.controller.Document;

import com.example.demo.entity.Shop;
import com.example.demo.model.ResponseData;
import com.mongodb.client.result.DeleteResult;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author hanqiang
 * @Classname DeleteDocumentController
 * @Date 2020/10/6 14:12
 * @Description:
 */
@RestController
@RequestMapping("/document")
public class DeleteDocumentController {

    @Autowired
    MongoTemplate mongoTemplate;

    private static final String COMMON_NAME="shops";

    @ApiOperation(value="对集合中删除数据",notes="删除数据")
    @PostMapping("/remove")
    public ResponseData remove() {
        Query query = Query.query(Criteria.where("price").is(12));
        DeleteResult remove = mongoTemplate.remove(query, Shop.class);
        return ResponseData.success(remove);
    }

    /**
     * 删除数据
     * 该方法在调用的时候一直报找不到类，所以还没有找到问题所在。
     */
    @ApiOperation(value="对集合中查询然后删除全部数据",notes="删除数据")
    @GetMapping("/findAllAndRemove")
    public ResponseData findAllAndRemove() {
        String name="han";
        Query query=new Query(Criteria.where("name").is(name));
        List<Shop> list=mongoTemplate.findAllAndRemove(query, Shop.class, COMMON_NAME);
        return ResponseData.success(list);

    }

    /**
     * 查询之后删除
     */
    @ApiOperation(value="集合查询然后删除数据",notes="删除数据")
    @GetMapping("/findAndRemove")
    public ResponseData findAndRemove(){
        Query query=new Query();
        Criteria criteria=Criteria.where("name").is("han");
        query.addCriteria(criteria);
        Shop Plist= mongoTemplate.findAndRemove(query, Shop.class, COMMON_NAME);
        return ResponseData.success(Plist);
    }
}
